﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ZEFIT
{

    public partial class LoginForm : Form
    {
        private Controller controller = null;
        private List<User> userList = null;

        public LoginForm()
        {
            InitializeComponent();
            try
            {
                MYSQLConnecter.myConnection.ConnectionString = "Data Source=localhost;Initial Catalog=ZEFIT;User Id=ZefitUser;Password=matriX28";
                controller = new Controller(new MYSQLAdabterUser());
                dataLoad();
            }
            catch (Exception e)
            {
                lbl_error.Text = "Datenbankfehler: " + e.ToString();
                lbl_error.Visible = true;
            }
        }

        private void dataLoad()
        {
            userList = new List<User>();
            foreach (List<object> tempList in controller.Select())
            {
                User temp = new User();
                temp.Id = (int)tempList[0];
                temp.FirstName = (String)tempList[1];
                temp.LastName = (String)tempList[2];
                temp.UserName = (String)tempList[3];
                temp.Email = (String)tempList[4];
                temp.Password = (String)tempList[5];
                temp.IsAdmin = (bool)tempList[6];
                temp.IsActive = (bool)tempList[7];
                userList.Add(temp);
            }
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if(txt_username.Text.Equals("")||txt_password.Text.Equals("")){
                lbl_error.Text = "Bitte alles ausfüllen";
                lbl_error.Visible = true;
                return;
            }
            String loginText = this.txt_username.Text;
            String passwort = this.txt_password.Text;
            User user = null;
            foreach (User tempUser in userList)
            {
                if (loginText == tempUser.UserName && passwort == tempUser.Password && tempUser.IsActive)
                {
                    user = tempUser;
                }
            }
            if (user == null)
            {
                lbl_error.Text = "Benutzername oder Passwort falsch";
                lbl_error.Visible = true;
            }
            else {
                this.Visible = false;
                MainForm mainForm = new MainForm(this, user);
                mainForm.Visible = true;
                mainForm.Show();
            }
        }

        public void logout()
        {
            dataLoad();
            this.txt_username.Text = "";
            this.txt_password.Text = "";
            this.Visible = true;
        }
    }
}
